package com.zhyz.bookstore.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

/**
 * 编码过滤器
 */
@WebFilter("/*")
public class EncodingFilter implements Filter {

    private static  String encoding;

    public void init(FilterConfig filterConfig) throws ServletException {
        encoding = filterConfig.getInitParameter("encoding");
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {

        if (encoding != null){
            //设置请求字符编码格式
            req.setCharacterEncoding(encoding);
            //设置相应字符编码格式
            resp.setCharacterEncoding(encoding);
        } else {
            req.setCharacterEncoding("UTF-8");
//            resp.setContentType("text/html;charset=utf-8");
        }
        //放行
        chain.doFilter(req,resp);
    }

    public void destroy() {

    }
}
